package com.sniper.web.utils;

import com.sniper.model.AdminRight;
import com.sniper.utils.DataUtil;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author suzhen
 * @create 2017/10/23
 */
public class DataWebUtil extends DataUtil {

    /**
     * @param value
     * @return
     */
    public static byte[] serialize(List<AdminRight> value) {
        if (value == null) {
            throw new NullPointerException("Can't serialize null");
        }
        byte[] rv;
        ByteArrayOutputStream bos = null;
        ObjectOutputStream os = null;
        try {
            bos = new ByteArrayOutputStream();
            os = new ObjectOutputStream(bos);
            for (AdminRight user : value) {
                os.writeObject(user);
            }
            os.writeObject(null);
            os.close();
            bos.close();
            rv = bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            throw new IllegalArgumentException("Non-serializable object", e);
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return rv;
    }

    public static List<AdminRight> deserialize(byte[] in) {
        List<AdminRight> list = new ArrayList<>();
        ByteArrayInputStream bis = null;
        ObjectInputStream is = null;
        try {
            if (in != null) {
                bis = new ByteArrayInputStream(in);
                is = new ObjectInputStream(bis);
                while (true) {
                    AdminRight user = (AdminRight) is.readObject();
                    if (user == null) {
                        break;
                    } else {
                        list.add(user);
                    }
                }
                is.close();
                bis.close();
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (bis != null) {
                    bis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return list;
    }
}
